let data = {};
let editingId = null;
let requestUrl = null;
/**
 * 装备穿戴状态
 */
let stateArray = ["未装备", "装备中"];
/**
 * 属性类型
 */
let typeArray = [null, "基础属性", "附加属性"];
/**
 * 子女装备类型
 */
let equipmentTypes = [null, "手镯", "吊坠", "脚环"];

function addHandler() {
	requestUrl = "/children_equipment/insert";

	$("#equipment_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");
	
	if (rowData) {
		requestUrl = "/children_equipment/updateById";

		$("#id").val(rowData.id);
		$("#forger").textbox("setValue", rowData.forger);
		$("#roleId").combobox("setValue", rowData.roleId);
		$("#skillId").combobox("setValue", rowData.skillId);
		$("#childrenId").combobox("setValue", rowData.childrenId);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#wearStatus").combobox("setValue", rowData.wearStatus);

		$("#equipment_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！");
	}
}

function deleteHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");
	
	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/children_equipment/deleteById", {
					id: rowData.id
				}, function(resp) {
					showMsg(resp.message);

					$("#equipment_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的记录！");
	}
}

function attributeHandler() {
	let rowData = $("#equipment_list").datagrid("getSelected");

	if (rowData) {
		requestUrl = "/children_equipment_attribute/updateById";

		$("#equipment_datalist").datalist("reload", {
			callback: function () {
				$("#equipment_datalist").datalist("selectRecord", rowData.id);
			}
		});

		$("#property_dialog").dialog("open");
	} else {
		unselected();
	}
}

function viewHandler() {
	// 子女装备属性
	$("#property_white").empty();
	$("#property_green").empty().hide();
	$("#property_blue").empty().hide();

	// 星石属性
	$("#xingshi").hide();
	$("#property_xingshi_base").empty().hide();
	$("#property_xingshi_fuling").empty().hide();
	$("#property_xianghun").empty().hide();

	let rowData = $("#equipment_list").datagrid("getSelected");

	if (rowData) {
		// 宠物装备详情——基本信息
		ajaxGet("/children_equipment_category/selectById", {
			id: rowData.categoryId
		}, function (resp) {
			let data = resp.data;

			$("#equipment_name").html(data.name);
			$("#equipment_note").html(data.note);
			$("#equipment_grade").html(data.grade);
			$("#equipment_image").attr("src", data.image);
			$("#equipment_type").html(equipmentTypes[data.type]);
		}, error);

		// 查询子女装备属性
		ajaxGet("/children_equipment_attribute/selectAttributes", {
			equipmentId: rowData.id
		}, function (resp) {
			let data = resp.data;

			if (data.length > 0) {
				$("#property").show();

				for (let i = 0; i < data.length; i++) {
					let attribute = data[i];

					if (attribute.propertyType === 1) { // 基础属性
						$("#property_white").html("&emsp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue);
					} else if (attribute.propertyType === 2) { // 附加属性
						$("#property_green").append("&emsp;" + attribute.propertyName + "+" + attribute.propertyValue  + "&emsp;").show();
					}
				}
			}
		}, error);

		if (rowData.skillId) {
			// 查询宠物技能信息
			ajaxGet("/chongwu_skill_category/selectById", {
				id: rowData.skillId
			}, function (resp) {
				let data = resp.data;

				if (data) {
					$("#property").show();

					$("#property_blue").append("&emsp;技能&ensp;" + data.name).show();
				}
			}, error);
		}

		// 查询子女装备镶嵌的星石
		ajaxGet("/xingshi/selectByEquipmentId", {
			equipmentId: rowData.id
		}, function (resp) {
			let data = resp.data;

			if (data) {
				$("#xingshi").show();

				let xingshiId = data.id;

				/**
				 * 查询星石属性
				 */
				ajaxGet("/xingshi/selectAttribute", {
					xingshiId: xingshiId
				}, function (resp) {
					let attribute = resp.data;

					if (attribute) {
						let property = "&emsp;" + data.grade + "级" + attribute.name;

						property += "&ensp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue;

						$("#property_xingshi_base").append(property).show();
					}
				}, error);

				/**
				 * 查询星石的附灵信息
				 */
				ajaxGet("/xingshi_fuling/selectAttributes", {
					xingshiId: xingshiId
				}, function (resp) {
					let data = resp.data;

					if (data && data.length > 0) {
						let content = "&emsp;";

						for (let i = 0; i <= data.length - 1; i++) {
							content += data[i].propertyName + "+" + data[i].propertyValue;

							if (i < data.length - 1) {
								content += "&emsp;&emsp;";
							}
						}

						$("#property_xingshi_fuling").append(content).show();
					}
				}, error);

				/**
				 * 查询星石的相魂属性
				 */
				ajaxGet("/xingshi_xianghun/selectByXingshiId", {
					xingshiId: xingshiId
				}, function (resp) {
					let data = resp.data;

					if (data) {
						$("#property_xingshi_xianghun").html("&emsp;" + data.effect).show();
					}
				}, error);
			}
		}, error);

		$("#equipment_forger").html(rowData.forger);

		$("#equipment_detail").dialog("open");
	}
}

$(document).ready(function() {

	/**
	 * 子女装备类型
	 */
	$("#category_id").combobox({
		url: "/children_equipment_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		prompt: "-装备类型-",
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 附加子女技能
	 */
	$("#skill_id").combobox({
		url: "/chongwu_skill_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		prompt: "-附加技能-",
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='18' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 子女
	 */
	$("#children_id").combobox({
		url: "/children/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		prompt: "-选择子女-",
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/children_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#children_" + row.id).attr({
					alt: data.name,
					src: data.image,
					title: data.name
				});
			}, error);

			return "<img width='18' id='children_" + row.id + "' />&nbsp;" + row.name;
		}
	});

	$("#role_id").combobox({
		url: "/role_account/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		prompt: "-选择角色-",
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#modeling_" + row.id).attr({
					"title": data.name,
					"src": data.image,
					"alt": data.name
				});
			}, error);

			return "<img height='18' id='modeling_" + row.id + "' />&nbsp;" + row.name;
		}
	});

	$("#search").linkbutton({
		iconCls: "icon-search"
	}).click(function() {
		let roleId = $("#role_id").combobox("getValue");
		let skillId = $("#skill_id").combobox("getValue");
		let childrenId = $("#children_id").combobox("getValue");
		let categoryId = $("#category_id").combobox("getValue");

		$("#equipment_list").datagrid("reload", {
			categoryId: categoryId,
			childrenId: childrenId,
			skillId: skillId,
			roleId: roleId
		});
	});

	$("#clear").linkbutton({
		iconCls: "icon-delete"
	}).click(function() {
		$("#search_form").form("clear");
	});

	/******************************************************************************************************/

	/**
	 * 子女装备类型
	 */
	$("#categoryId").combobox({
		url: "/children_equipment_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 打造者
	 */
	$("#forger").textbox({
		width: 150,
		required: true
	});

	/**
	 * 附加子女技能
	 */
	$("#skillId").combobox({
		url: "/chongwu_skill_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='18' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 角色
	 */
	fetchRoleId();

	/**
	 * 子女
	 */
	$("#childrenId").combobox({
		url: "/children/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/children_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#child_" + row.id).attr({
					alt: data.name,
					src: data.image,
					title: data.name
				});
			}, error);

			return "<img width='18' id='child_" + row.id + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 穿戴状态
	 */
	fetchSelect("#wearStatus", stateArray, {
		width: 150,
		required: true
	});
	
	$("#equipment_dialog").dialog({
		title: "子女装备",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#equipment_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#equipment_dialog").dialog("close");
						$("#equipment_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#equipment_form").form("clear");
				$("#equipment_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * 子女装备列表
	 */
	$("#equipment_datalist").datalist({
		url: "/children_equipment/selectAll",
		width: 222,
		height: 308,
		idField: "id",
		valueField: "id",
		textField: "categoryId",
		textFormatter: function(value, rowData, rowIndex) {
			ajaxGet("/children_equipment_category/selectById", {
				id: rowData.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#children_equipment_" + rowData.id).prop({
					"src": data.image,
					"title": data.name
				});
			}, error);

			if (rowData.skillId) {
				ajaxGet("/chongwu_skill_category/selectById", {
					id: rowData.skillId
				}, function (resp) {
					let data = resp.data;

					$("#skill_" + rowData.id).html(data.name).addClass("blue");
				}, error);
			}

			return "<table>" +
				"<tr>" +
				"<td rowspan='2'><img height='50' id='children_equipment_" +  rowData.id + "' /></td>" +
				"<td>打造：<span>" + rowData.forger + "</span></td>" +
				"</tr>" +
				"<tr>" +
				"<td>技能：<span id='skill_" + rowData.id + "'>无</span></td>" +
				"</tr>" +
				"</table>";
		},
		onSelect: function(rowIndex, rowData) {
			if(rowData) {
				$("#property_list").datagrid("reload", {
					equipmentId: rowData.id
				});
			}
		}
	});

	/**
	 * 子女装备属性列表
	 */
	$("#property_list").datagrid({
		url: "/children_equipment_attribute/selectByEquipmentId",
		method: "get",
		title: "子女装备属性列表",
		width: 456,
		height: 276,
		onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
			data = {
				id: rowData.id,
				type: rowData.type,
				equipmentId: rowData.equipmentId,
				propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
				propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let rowData = $("#equipment_datalist").datalist("getSelected");

				if(rowData) {
					let list = $("#property_list");
					
					list.datagrid("appendRow",{
						equipmentId: rowData.id,
						propertyId: null,
						propertyValue: 1,
						type: null
					});

					let total = list.datagrid("getRows").length;

					editingId = total - 1;
					requestUrl = "/children_equipment_attribute/insert";

					list.datagrid("beginEdit", editingId);
				} else {
					unselected("请选择一件器灵~");
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let list = $("#property_list");

				if (editingId != null) {
					list.datagrid("selectRow", editingId);
				} else {
					let row = list.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = list.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/children_equipment_attribute/updateById";

						list.datagrid("beginEdit", rowIndex);

						let $editor = list.datagrid("getEditor", {
							index: rowIndex,
							field: "propertyId"
						});

						let rowData = $("#equipment_list").datagrid("getSelected");

						$($editor.target).combobox("reload", {
							equipmentId: rowData.categoryId
						});
					} else {
						alertMsg("请选择要修改的记录！", "warning");
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#property_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#property_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#property_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#property_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/children_equipment_attribute/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#property_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					unselected();
				}
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "equipmentId", hidden: true},
			{field: "propertyId", title: "属性", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/children_equipment_view_attribute/selectByEquipmentId",
						valueField: "id",
						textField: "name",
						panelHeight: "auto"
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/property/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#propperty_" + rowIndex).html(data.name);
						}, error);

						return "<span class='blue' id='propperty_" + rowIndex + "'></span>";
					}
				}
			},
			{field: "propertyValue", title: "属性值", align: "center", width: 150
				, editor: {
					type: "numberspinner",
					options: {
						min: 1
					}
				}
			},
			{field: "type", title: "属性类型", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						data: getJsonData(typeArray)
					}
				}
				, formatter: function(value) {
					return "<span>" + typeArray[value] + "</span>";
				}
			}
		]]
	});

	/**
	 * 子女装备属性对话框
	 */
	$("#property_dialog").dialog({
		title: " "
	});

	/******************************************************************************************************/

	$("#equipment_detail > .splitter").textbox({
		width: 200
	});

	/**
	 * 子女装备详情对话框
	 */
	$("#equipment_detail").dialog({
		title: " ",
		width: 220
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	$("#equipment_list").datagrid({
		url: "/children_equipment/selectByPage",
		height: height_table,
		rownumbers: true,
		fitColumns: true,
		pagination: true,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "设置属性",
			handler: function() {
				attributeHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "查看详情",
			handler: function() {
				viewHandler();
			}
		}],
		columns: [[
			{field: "id", title: "编号", align: "center", hidden: true},
			{field: "categoryId", title: "装备类型", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/children_equipment_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#equipment_" + rowIndex).attr({
							alt: data.name,
							src: data.image,
							title: data.name
						}).tooltip({
					        position: "right",
					        content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
					        onShow: function() {
					    		$(this).tooltip("tip").css({
					    			backgroundColor: "#666",
					    			borderColor: "#666"
					    		});
					        }
					    });
					}, error);
					
					return "<img height='" + size + "' id='equipment_" + rowIndex + "' />";
				}
			},
			{field: "forger", title: "打造者", align: "center", width: 160},
			{field: "skillId", title: "附加技能", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					if(value) {
						ajaxGet("/chongwu_skill_category/selectById", {
							id: value
						}, function(resp) {
							let data = resp.data;

							$("#skill_" + rowIndex).attr({
								alt: data.name,
								src: data.image
							}).tooltip({
						        position: "left",
						        content: "<span class='white'>" + data.name + "：" + data.note + "</span>",
						        onShow: function() {
						    		$(this).tooltip("tip").css({
						    			backgroundColor: "#666",
						    			borderColor: "#666"
						    		});
						        }
						    });
						}, error);
						
						return "<img height='" + size + "' id='skill_" + rowIndex + "' />";
					}

					return "/";
				}
			},
			{field: "childrenId", title: "穿戴子女", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					if(value) {
						ajaxGet("/children/selectById", {
							id: value
						}, function(resp) {
							let children = resp.data;

							ajaxGet("/children_category/selectById", {
								id: children.categoryId
							}, function(resp) {
								let data = resp.data;

								$("#children_" + rowIndex).attr({
									alt: children.name,
									src: data.image
								}).tooltip({
									position: "left",
									content: "<span class='white'>" + children.name + "</span>",
									onShow: function() {
										$(this).tooltip("tip").css({
											backgroundColor: "#666",
											borderColor: "#666"
										});
									}
								});
							}, error);
						}, error);

						return "<img height='" + size + "' id='children_" + rowIndex + "' />";
					}

					return "/";
				}
			},
			roleDetailsColumn
		]]
	});

});